#include "thread_pool.hpp"
#define FILENAME "1a.txt"
int recvn(int sockfd, void *buff, int len)
{
    int left = len;
    int ret = 0;
    char *pbuf = (char *)buff;
    while (left > 0)
    {
        ret = recv(sockfd, pbuf, left, 0);
        if (ret < 0)
        {
            perror("recv");
            return -1;
        }
        else if (ret == 0)
        {
            break;
        }
        pbuf += ret;
        left -= ret;
    }
    return len - left;
}
int sendn(int sockfd, const void *buff, int len)
{
    int left = len;
    int ret = 0;
    const char *pbuf = (const char *)buff;
    while (left > 0)
    {
        ret = send(sockfd, pbuf, left, 0);
        if (ret == -1)
        {
            perror("send");
            return -1;
        }
        pbuf += ret;
        left -= ret;
    }
    return len - left;
}
int transferFile(int peerfd)
{
    int fd = open(FILENAME, O_RDWR);
    ERROR_CHECK(fd, -1, "open");
    train_t t;
    memset(&t, 0, sizeof(t));
    t.len = strlen(FILENAME);
    strcpy(t.buff, FILENAME);
    send(peerfd, &t, 4 + t.len, 0);
    struct stat st;
    memset(&st, 0, sizeof(st));
    fstat(fd, &st);
    printf("filelength: %ld\n", st.st_size);
    printf("sizeof(st.st_size): %ld\n", sizeof(st.st_size));
    send(peerfd, &st.st_size, sizeof(st.st_size), 0);
    while (1)
    {
        memset(&t, 0, sizeof(t));
        int ret = read(fd, t.buff, sizeof(t.buff));
        if (ret != 1000)
        {
            printf("read ret: %d\n", ret);
        }
        if (ret == 0)
        {
            break;
        }
        t.len = ret;
        ret = sendn(peerfd, &t, 4 + t.len);
        if (ret == -1)
        {
            break;
        }
        if (ret != 1004)
        {
            printf("send ret: %d\n", ret);
        }
    }
    printf("send file over.\n");
    close(fd);
}